#include "tj_form_barcode_return.h"
#include "ui_tj_form_barcode_return.h"

#include "pub_var.h"
#include <QSettings>
#include <QMessageBox>
#include <QJsonDocument>
#include <QNetworkReply>
#include <QSqlError>
#include <QTimer>
#include <QCloseEvent>

tj_form_barcode_return::tj_form_barcode_return(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::tj_form_barcode_return)
{
    ui->setupUi(this);

    ui->pushButton_2->setVisible(false);//接收默认回车信号

    //恢复当前窗口位置
    QSettings setIni("clin.ini", QSettings::IniFormat);
    QRect rct = setIni.value("windowState/form_barcode_return").toRect();
    this->setGeometry(rct);

    ui->pb_exit->setVisible(false);

    //数据库连接
    qrm = new QSqlQuery(pub::db_m);
    qrmt = new QSqlQuery(pub::db_m);

    qro = new QSqlQuery(pub::db_o);
    qrot = new QSqlQuery(pub::db_o);

    md_item_list = new QSqlQueryModel();

    sq = "create temporary table if not exists "
         "tmp_recipe_return_code "
         "("
         "item_code VARCHAR(12), " //项目编码
            "item_name VARCHAR(100),"  //项目名称
            "bar_code_base varchar(20),"    //溯源码包含的药品识别码
            "bar_code varchar(40) not null,"    //溯源码
            "bar_code_count int,"    //溯源码计数
            "bar_code_ret varchar(40),"    //溯源码
            "bar_code_ret_count int,"    //溯源码计数
            "rec_sn varchar(40), " //等于 fin_opb_feedetail.mo_order 和 met_order_recipedetail.sequence_no';
            "clinic_code varchar(20)," //clinic_code
            "recipe_no varchar(20),"    //处方号
            "card_no varchar(20)"    //病志号
            ")";

    qDebug()<<"建立临时表 tmp_recipe_return_code : "<<sq;

    if(!qrm->exec(sq))
    {
        QMessageBox::information(this, "注意", "无法新建临时表 tmp_recipe_return_code ！\n" + qrm->lastError().text());
        return;
    }

    sq = "ALTER TABLE tmp_recipe_return_code ADD UNIQUE INDEX index3 (bar_code ASC, recipe_no ASC)";
    if(!qrm->exec(sq))
    {
        QMessageBox::information(this, "注意", "无法为临时表 tmp_recipe_return_code 创建唯一索引！\n" + qrm->lastError().text());
        return;
    }


    //条码录入时限，为兼容扫描器硬件失灵不能送出回车信号
    tm_code_input = new QTimer(this);
    connect(tm_code_input, &QTimer::timeout, this, &tj_form_barcode_return::tm_code_input_timeout);

    //
    tm_display_delay = new QTimer(this);
    connect(tm_display_delay, &QTimer::timeout, this, &tj_form_barcode_return::tm_display_delay_timeout);
}

tj_form_barcode_return::~tj_form_barcode_return()
{
    delete ui;
}

void tj_form_barcode_return::tm_code_input_timeout()
{
    tm_code_input->stop();
    on_le_code_returnPressed();
}

void tj_form_barcode_return::closeEvent(QCloseEvent *event)
{

    qDebug()<<"value_saved is "<< value_saved<<"\n";

    if(!value_saved)
    {
        QMessageBox::information(this, "Note", "请通过保存按钮关闭窗口！");
        event->ignore();
        return;
    }

    QSettings setIni("clin.ini", QSettings::IniFormat);
    setIni.setValue("windowState/form_barcode_return", QVariant(this->geometry()));
    //destroyW("barcode_return");

}

void tj_form_barcode_return::on_le_code_returnPressed()
{
    //如果当前有扫码延时，停止
    if(tm_code_input->isActive())
    {
        tm_code_input->stop();
    }

    QString code = ui->le_code->text().trimmed();

    if(code.isEmpty())
    {
        return;
    }

    sq = " update tmp_recipe_return_code "
         " set "
         " bar_code_ret = '%1', "
         " bar_code_ret_count = bar_code_count "
         " where"
         " bar_code_ret_count < bar_code_count and bar_code = '%1'";
    sq = sq.arg(code);

    qDebug()<<"保存返回药品码至临时表："<<sq;

    qrm->exec(sq);
    if(qrm->numRowsAffected() < 1)
    {
        QMessageBox::critical(this, "注意", "条码无效，保存失败！");
        ui->le_code->setFocus();
        ui->le_code->selectAll();
        return;
    }

    current_status = "item_code_return";

    tm_display_delay_timeout();

}

void tj_form_barcode_return::on_pb_exit_clicked()
{
    //清空旧临时数据
    qrm->exec("delete from tmp_recipe_return_code");

    this->close();
}

void tj_form_barcode_return::on_pb_save_clicked()
{

    //保存
    qDebug()<<"保存中间数据至pha_sto_barcode_return\n";
    sq = " select * from tmp_recipe_return_code ";
    qrm->exec(sq);
    while(qrm->next())
    {
        sq = "insert into pha_sto_barcode_return"
             "("
             " rec_sn, bar_code, bar_code_base, clinic_code,"//0-3
             " recipe_no, card_no, bar_code_count, drug_code, "//4-7
             " scaned, reused, scan_date"//8-10
             ") values (";
        //0-3
        sq += qrm->value("rec_sn").toString() + ",";
        sq += "'" + qrm->value("bar_code").toString() + "',";
        sq += "'" + qrm->value("bar_code_base").toString() + "',";
        sq += "'" + qrm->value("clinic_code").toString() + "',";
        //4-7
        sq += "'" + qrm->value("recipe_no").toString() + "',";
        sq += "'" + qrm->value("card_no").toString() + "',";
        sq += qrm->value("bar_code_count").toString() + ",";
        sq += "'" + qrm->value("item_code").toString() + "',";
        //8-10
        if( qrm->value("bar_code_ret_count").toInt() < 1)
        {
            sq += "'0',";//追溯码未扫描
        }
        else
        {
            sq += "'1',";//追溯码已扫描
        }

        sq += "'0', sysdate";
        sq += ")";

        qDebug()<<"保存返回的追溯码："<<sq<<"\n";

        qro->exec(sq);
    }

    sq = " update tmp_recipe_return_code "
         " set bar_code_ret = bar_code, bar_code_ret_count = bar_code_count";
    qrm->exec(sq);
    value_saved = true;
    this->close();
}

void tj_form_barcode_return::on_le_code_textChanged(const QString &arg1)
{
    if(current_status == "recipe_content_clicked")
    {
        return;
    }

    if(arg1.trimmed().isEmpty())
    {
        return;
    }

    if(tm_code_input->isActive())
    {
        tm_code_input->stop();
    }
    tm_code_input->start(200);
}

void tj_form_barcode_return::prepare_display(QString barcode_list, QString recipe_list)
{

    //清空旧临时数据
    qrm->exec("delete from tmp_recipe_return_code");

    //提取窗口药品关联过的条码

    sq = " select INFO.TRADE_NAME, BREC.bar_code, brec.bar_code_count,"
         " info.drug_code, brec.bar_code_base, brec.rec_sn, "
         " brec.clinic_code, brec.recipe_no, reg.card_no"
         " from pha_sto_barcode_rec brec"
         " LEFT JOIN PHA_COM_BASEINFO info on INFO.ID_CODE = brec.BAR_CODE_BASE"
         " left join fin_opr_register reg on reg.clinic_code = brec.clinic_code"
         " where brec.BAR_CODE in(" + barcode_list +
            ") and brec.recipe_no in (" + recipe_list + ")";
    sq += " and brec.valid_state = '1' and brec.bar_code_count > 0 ";
    qDebug()<<"提取窗口药品关联过的条码："<<sq;
    qro->exec(sq);
    while(qro->next())
    {
        sq = "insert into tmp_recipe_return_code ("
             " item_name, bar_code, bar_code_count, bar_code_ret, bar_code_ret_count,"
             " item_code, bar_code_base, rec_sn, clinic_code, recipe_no, card_no "
             " )values (";
        sq += "'" + qro->value("TRADE_NAME").toString() + "',";
        sq += "'" + qro->value("bar_code").toString() + "',";
        sq += qro->value("bar_code_count").toString() + ", '', 0, ";
        sq += "'" + qro->value("drug_code").toString() + "',";
        sq += "'" + qro->value("bar_code_base").toString() + "',";
        sq += "'" + qro->value("rec_sn").toString() + "',";
        sq += "'" + qro->value("clinic_code").toString() + "',";
        sq += "'" + qro->value("recipe_no").toString() + "',";
        sq += "'" + qro->value("card_no").toString() + "'";
        sq += ")";

        qDebug()<<"保存条码至临时表："<<sq;
        qrm->exec(sq);
    }


    tm_display_delay->start(50);
}

void tj_form_barcode_return::tm_display_delay_timeout()
{
    if(tm_display_delay->isActive())
    {
        tm_display_delay->stop();
    }

    sq = "select item_name 药品名称, "
         "bar_code 付药追溯码, "
         "bar_code_count 数量, "
         "bar_code_ret 返回追溯码, "
         "bar_code_ret_count 数量 "
         " from tmp_recipe_return_code ";
    qDebug()<<"显示临时表条码："<<sq;
    md_item_list->setQuery(sq, pub::db_m);
    ui->tv_item_list->setModel(md_item_list);


    pub::setColumnWidth(ui->tv_item_list, "0.27^0.27^0.06^0.27^0.06", ui->tv_item_list->width());
    ui->le_code->setFocus();
    ui->le_code->clear();
}

QList<QMap<QString, QString>> tj_form_barcode_return::return_values()
{
    QList<QMap<QString, QString>> ret_values;
    QMap<QString, QString> mp;

    sq = "select item_name, bar_code, bar_code_count, bar_code_ret, bar_code_ret_count,"
         " item_code, bar_code_base, rec_sn, clinic_code, recipe_no  from tmp_recipe_return_code ";

    qrm->exec(sq);
    while(qrm->next())
    {
        mp["item_name"] = qrm->value("item_name").toString();
        mp["bar_code"] = qrm->value("bar_code").toString();
        mp["bar_code_count"] = qrm->value("bar_code_count").toString();
        mp["bar_code_ret"] = qrm->value("bar_code_ret").toString();
        mp["bar_code_ret_count"] = qrm->value("bar_code_ret_count").toString();
        mp["item_code"] = qrm->value("item_code").toString();
        mp["bar_code_base"] = qrm->value("bar_code_base").toString();
        mp["rec_sn"] = qrm->value("rec_sn").toString();
        mp["clinic_code"] = qrm->value("clinic_code").toString();
        mp["recipe_no"] = qrm->value("recipe_no").toString();

        ret_values << mp;

    }

    return ret_values;

}
QString tj_form_barcode_return::return_codes()
{
    QString ret = "";

    sq = "select bar_code_ret, bar_code_ret_count from tmp_recipe_return_code ";

    qrm->exec(sq);
    while(qrm->next())
    {
        ret += qrm->value(0).toString() + "^" + qrm->value(1).toString() + "^";
    }

    return ret;
}

void tj_form_barcode_return::on_pb_retrive_clicked()
{
    if(ui->tv_item_list->currentIndex().isValid())
    {
        QString code = ui->tv_item_list->currentIndex().siblingAtColumn(1).data().toString();
        sq = "update tmp_recipe_return_code set "
             " bar_code_ret_count = 0  where  bar_code = '" + code + "'";
        qrm->exec(sq);
        tm_display_delay_timeout();
    }
    else
    {
        QMessageBox::information(this, "注意", "未指定药品项目！");
        return;
    }
}

void  tj_form_barcode_return::set_value_saved(bool set_value)
{
    //启动此窗口前，应设置 value_saved 为 false， 做为窗口内容是否保存的标志。
    qDebug()<<"set saved value to "<<set_value<<"\n";
    value_saved = set_value;
}
